import Vue from 'vue'
import router from '@/router'
import store from '@/store'

/**
 * 获取uuid
 */
export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth (key) {
  return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

/**
 * 清除登录信息
 */
export function clearLoginInfo () {
  Vue.cookie.delete(window.SITE_CONFIG['tokenKey'])
  Vue.cookie.delete(window.SITE_CONFIG['tenantKey'])
  store.commit('resetStore')
  router.options.isAddDynamicMenuRoutes = false
}

/**
 * 请求头
 */
export function getHeaders () {
  return {
    'token': Vue.cookie.get(window.SITE_CONFIG['tokenKey']),
    'tenantId': Vue.cookie.get(window.SITE_CONFIG['tenantKey']) || ''
  }
}

/**
 * 获得或缓存国际化语言
 */
export function langStorage (value) {
  let key = 'boot-lang-admin'
  if (value) {
    window.localStorage.setItem(key, value)
  } else {
    return window.localStorage.getItem(key) || 'zh'
  }
}

/**
 * 获得国际化语言标识 和网页标题
 */
export function languageTag () {
  let cache = langStorage()
  let result = {
    title: '运营管理系统',
    language: 'zh_CN'
  }
  if (cache === 'zh') { // 简体中文
    return result
  } else if (cache === 'en') { // 英语
    result.title = 'Management System'
    result.language = 'en_US'
  } else if (cache === 'cht') { // 繁体中文
    result.title = '運營管理系統'
    result.language = 'zh_CHT'
  }
  return result
}

/**
 * 年月日格式化
 * @param dateNow
 */
export function getYMD (dateNow) {
  let now
  if (typeof dateNow === 'string') {
    now = new Date(dateNow)
  } else if (dateNow instanceof Date) {
    now = dateNow
  } else {
    now = new Date()
  }
  let fullYear = now.getFullYear() // 获取完整的年份(4位)
  let month = now.getMonth() + 1 // 获取当前月份(0-11,0代表1月)
  let date = now.getDate() // 获取当前日(1-31)
  if (month < 10) {
    month = '0' + month
  }
  if (date < 10) {
    date = '0' + date
  }
  return fullYear + '-' + month + '-' + date
}
